// 翻转名片
function rotateCard() {
  const cardBox = document.querySelector(".card-container");
  cardBox.classList.toggle("flipped");
}

// 发名片
function sendCard(text, url) {
  openPopup("popupCard");
  createQRCode(text, url);
}

// toast
let timer = null;
function showToast(message) {
  const toast = document.getElementById("toast");
  if (timer) {
    clearTimeout(timer);
    toast.hidden = true;
    timer = null;
  }
  toast.textContent = message;
  toast.hidden = false;
  timer = setTimeout(() => {
    toast.hidden = true;
    timer = null;
  }, 3000);
}

// 打开弹窗
function openPopup(id) {
  $("#" + id).show();
}
// 关闭客服弹窗
function closePopup(id) {
  $("#" + id).hide();
}

hasCreateQRCode = false;
// 生成二维码
function createQRCode(text, url) {
  if (hasCreateQRCode) {
    return;
  }
  new QRCode(document.getElementById("qrcode"), {
    text: url,
    width: 750, // 宽度(百分比 no)
    height: 750, // 高度(百分比 no)
    colorDark: "#333333", // 生成的二维码的深色部分
    colorLight: "#ffffff", // 生成二维码的浅色部分
    background: "#ffffff", // 背景颜色
    foreground: "#333333", // 前景颜色
    margin: 0, // 先将库的 margin 设为 0
  });

  // 获取生成的 canvas 元素
  const canvas = document.getElementById("qrcode").querySelector("canvas");
  if (canvas) {
    const margin = 60; // 自定义边距值
    const textHeight = 60; // 文本高度
    const maxCharsPerLine = 15; // 每行最大字符数
    const lines = [];
    for (let i = 0; i < text.length; i += maxCharsPerLine) {
      lines.push(text.slice(i, i + maxCharsPerLine));
    }
    const originalWidth = canvas.width;
    const originalHeight = canvas.height;

    // 创建一个新的 canvas 并设置边距
    const newCanvas = document.createElement("canvas");
    newCanvas.width = originalWidth + 2 * margin;
    newCanvas.height = originalHeight + 2 * margin + textHeight * lines.length;
    const ctx = newCanvas.getContext("2d");
    ctx.fillStyle = "#ffffff"; // 设置背景颜色
    ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);
    ctx.drawImage(canvas, margin, margin);

    // 绘制文本
    ctx.font = "50px 微软雅黑"; // 设置字体样式和大小
    ctx.fillStyle = "#606266"; // 设置文本颜色
    ctx.textAlign = "center"; // 设置文本对齐方式.

    const lineHeight = 60; // 行高
    let y = originalHeight + margin + textHeight;
    lines.forEach((line) => {
      ctx.fillText(line, newCanvas.width / 2, y);
      y += lineHeight;
    });

    // 生成图片
    const img = document.createElement("img");
    img.src = newCanvas.toDataURL("image/png");
    img.style = "width: 100%";
    // 替换原来的 canvas
    const qrcodeContainer = document.getElementById("qrcode");
    qrcodeContainer.innerHTML = "";
    newCanvas.style = "width: 100%";
    // qrcodeContainer.appendChild(newCanvas);
    qrcodeContainer.appendChild(img);
    hasCreateQRCode = true;
  }
}

// // 保存图片
// function onDownload(name) {
//   let canvas = document.getElementById("qrcode").querySelector("canvas");
//   if (!canvas) {
//     showToast("请先生成二维码");
//     return;
//   }
//   canvas.toBlob((blob) => {
//     if (!blob) {
//       showToast("图片生成失败");
//       return;
//     }
//     const a = document.createElement("a");
//     a.href = URL.createObjectURL(blob);
//     a.download = `${name}-电子名片1.png`;
//     a.click();
//   }, "image/png");
// }
// // 保存图片
// function onDownload(name) {
//   let canvas = document.getElementById("qrcode").querySelector("canvas");
//   let img = canvas.toDataURL("image/png");
//   let a = document.createElement("a");
//   a.download = `${name}-电子名片.png`;
//   a.href = img;
//   a.click();
// }

// 页面滚动到10vw,给fixed-top加白色背景
function addWhiteBg() {
  const fixedTop = document.querySelector(".fixed-top");
  if (window.scrollY > 5 * (window.innerWidth / 100)) {
    fixedTop.style.backgroundColor = "#edf1f8";
  } else {
    fixedTop.style.backgroundColor = "";
  }
}

// 页面滚动事件
window.addEventListener("scroll", addWhiteBg);
addWhiteBg();

// 立即联系
function openMessagePopup(uid) {
  form.uid = uid;
  openPopup("popupMessage");
}

// 更新输入框字数
function updateTextCount() {
  const textarea = document.getElementById("desc");
  const countElement = document.getElementById("descCount");
  const maxLength = 200;
  const currentLength = textarea.value.length;
  countElement.textContent = currentLength;
  if (currentLength > maxLength) {
    textarea.value = textarea.value.substring(0, maxLength);
    countElement.textContent = maxLength;
  }
}

// 提交留言
let form = {
  uid: "",
  name: "",
  phone: "",
  desc: "",
};
let rule = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  desc: [{ required: true, message: "请输入补充内容", trigger: "blur" }],
};
let loadingSubmit = false;
function onSubmitMessage() {
  if (loadingSubmit) {
    return;
  }
  if (validate()) {
    loadingSubmit = true;
    console.log(form);
    showToast("提交成功");
    setTimeout(() => {
      closePopup("popupMessage");
      loadingSubmit = false;
    }, 1000);
  }
}
function validate() {
  form.name = $("input[name='name']").val().trim();
  form.phone = $("input[name='phone']").val().trim();
  form.desc = $("textarea[name='desc']").val().trim();
  let rersult = true;
  for (let key in rule) {
    rule[key].forEach((item) => {
      if (rersult) {
        if (item.required && !form[key].trim()) {
          showToast(item.message);
          rersult = false;
        }
        if (item.pattern && !item.pattern.test(form[key])) {
          showToast(item.message);
          rersult = false;
        }
      }
    });
  }
  return rersult;
}
